package com.bhs.sansonglogistics.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

import com.bhs.sansonglogistics.base.Constants;
import com.github.mikephil.charting.utils.Utils;
import com.luck.picture.lib.utils.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

public class WxShareUtils {
    /**
     * 分享网页类型至微信
     *
     * @param context 上下文
     * @param webUrl  网页的url
     * @param title   网页标题
     * @param content 网页描述
     * @param bitmap  位图
     */
    public static void shareWeb(Context context, String webUrl, String title, String content, Bitmap bitmap) {
        // 通过appId得到IWXAPI这个对象
        IWXAPI wxapi = WXAPIFactory.createWXAPI(context, Constants.APP_ID);
        // 检查手机或者模拟器是否安装了微信
        if (!wxapi.isWXAppInstalled()) {
            ToastUtil.show("您还没有安装微信");
            return;
        }

        // 初始化一个WXWebpageObject对象
        WXWebpageObject webpageObject = new WXWebpageObject();
        // 填写网页的url
        webpageObject.webpageUrl = webUrl;

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage(webpageObject);
        // 填写网页标题、描述、位图
        msg.title = title;
        msg.description = content;
        // 如果没有位图，可以传null，会显示默认的图片
        msg.setThumbImage(bitmap);

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = "webpage";
        // 上文的WXMediaMessage对象
        req.message = msg;
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneSession;

        // 向微信发送请求
        wxapi.sendReq(req);
    }

    public static void shareBmp(Context context, Bitmap bmp) {
        shareBmp(context, bmp, SendMessageToWX.Req.WXSceneSession);
    }

    public static void shareBmp(Context context, Bitmap bmp, int type) {
        // 通过appId得到IWXAPI这个对象
        IWXAPI wxapi = WXAPIFactory.createWXAPI(context, Constants.APP_ID);
        // 检查手机或者模拟器是否安装了微信
        if (!wxapi.isWXAppInstalled()) {
            ToastUtil.show("您还没有安装微信");
            return;
        }
//初始化 WXImageObject 和 WXMediaMessage 对象
        WXImageObject imgObj = new WXImageObject(bmp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
//设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 200, 200, true);
//设置缩略图
        msg.thumbData = bmpToByteArray(thumbBmp);

//构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = type;
        req.userOpenId = Constants.APP_ID;
//调用api接口，发送数据到微信
        wxapi.sendReq(req);
    }

    // todo Bitmap转换为 byte数组
    public static byte[] bmpToByteArray(final Bitmap bmp) {
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);

        while (true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
            bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                // F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }

    /**
     * 分享微信小程序
     * @param context
     * @param webUrl
     * @param title
     * @param content
     */
    public static void shareMiniPro(Context context, String webUrl, String title, String content, Bitmap bitmap){
        // 通过appId得到IWXAPI这个对象
        IWXAPI wxapi = WXAPIFactory.createWXAPI(context, Constants.APP_ID);
        // 检查手机或者模拟器是否安装了微信
        if (!wxapi.isWXAppInstalled()) {
            ToastUtil.show("您还没有安装微信");
            return;
        }
        WXMiniProgramObject miniProgram = new WXMiniProgramObject();
        miniProgram.webpageUrl="/page_order/companyDetails/index";//自定义
        miniProgram.userName="gh_f6589072e372";//小程序端提供参数
        miniProgram.path=webUrl;//小程序端提供参数
        WXMediaMessage mediaMessage = new WXMediaMessage(miniProgram);
        mediaMessage.title = title;//自定义
        mediaMessage.description = content;//自定义
        mediaMessage.thumbData = bmpToByteArrayBySize(bitmap,128,false);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "";
        req.scene = SendMessageToWX.Req.WXSceneSession;
        req.message = mediaMessage;
        wxapi.sendReq(req);
    }

    private static byte[] bmpToByteArrayBySize(Bitmap bmp , int maxSize , Boolean isWithAlpha) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //压缩的格式（如果被压缩的图片带有透明度需要选择PNG)
        Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
        if (isWithAlpha) {
            compressFormat = Bitmap.CompressFormat.PNG;
        }
        //压缩的质量（压缩质量范围0-100，值越大，质量越好，对于 PNG 和 WEBP 格式，此参数不起作用，可以设置为 0）
        int compressQuality = 100;
        //将位图压缩为指定格式
        bmp.compress(compressFormat, compressQuality, byteArrayOutputStream);
        //判断压缩后的输出流是否符合指定的条件
        while ((byteArrayOutputStream.size() / 1024) > maxSize) {
            compressQuality -= 10;
            if (compressQuality <= 0) {
                break;
            }
            byteArrayOutputStream.reset();
            bmp.compress(compressFormat, compressQuality, byteArrayOutputStream);
        }
        return byteArrayOutputStream.toByteArray();
    }


}


